package chat;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

public class ConsultarSalaServiceImpl extends UnicastRemoteObject implements ConsultarSalaService{
	
	private List<Sala> lista;
	
	private int fimEndereco = 34;
	
	public ConsultarSalaServiceImpl() throws RemoteException{
        super();
    }
	
	@Override
	public List<Sala> listar() throws RemoteException {
		
		if(lista != null) return lista;
		
		lista = new ArrayList<Sala>();
        try {
            BufferedReader in = new BufferedReader(new FileReader("Salas.txt"));
            while (in.ready()) {
                String line = in.readLine();
                String elementos[] = line.split("::");
                System.out.println("limite: "+elementos[1]);
                String nome = elementos[0];
                int limiteUsuarios = Integer.parseInt(elementos[1]);
                String endereco = elementos[2];
                System.out.println("porta: "+elementos[3]);
                int porta = Integer.parseInt(elementos[3]);
                System.out.println("int: "+porta);
                lista.add(new Sala(nome, limiteUsuarios, endereco, porta));
            }
        } catch (FileNotFoundException ex) {
            return null;
        } catch (IOException io) {
            return null;
        }
        
		return lista;
	}

	@Override
	public List<String> usuariosPorSala(int salaIndex) {
		return lista.get(salaIndex).getConectados();
	}

	public void addUsuarioConectado(int salaIndex, String login){
		this.lista.get(salaIndex).getConectados().add(login);
	}
	
	public void removeUsuarioConectado(int salaIndex, String login){
		this.lista.get(salaIndex).getConectados().remove(login);
	}

	@Override
	public void criarSalaReservada(String nome, int limiteUsuarios, List<String> logins) throws RemoteException {
		String endereco = "228.5.6."+fimEndereco++;
		this.lista.add(new Sala(nome, limiteUsuarios, endereco, logins));
	}
}
